<?php

include_once '..//util/arrayutil.php';

class Category {

    private $id;
    private $name;
    private $description;

    public function setId($_id) {
        $this->id = $_id;
    }

    public function getId() {
        return $this->id;
    }

    public function setName($_name) {
        $this->name = $_name;
    }

    public function getName() {
        return $this->name;
    }

    public function setDescription($_des) {
        $this->description = $_des;
    }

    public function getDescription() {
        return $this->description;
    }

    public function save() {
        mysql_query("insert into category(name,description) 
                values('$this->name','$this->description')") or die("success:false,data:".mysql_error());
    }

    public function delete() {
        mysql_query("delete from category where id=$this->id") or die("success:false,row:".  mysql_error());
    }

    public function update() {
        mysql_query("update category set name='$this->name', description='$this->description' 
                where id=$this->id");
    }

    public static function load($id) {
        $result = mysql_query("select id,name,description from category where id=$id")
                or die(mysql_error());
        $row = mysql_fetch_row($result);
        $category = new Category();
        $category->id = $row[0];
        $category->name = $row[1];
        $category->description = $row[2];
        return $category;
    }

    public static function loads($start,$end) {
        $result = mysql_query("select id,name,description from category limit $start,$end");
        $categories = array();
        while ($row = mysql_fetch_array($result)) {
            $category = new Category();
            $category->id = $row['id'];
            $category->name = $row['name'];
            $category->description = $row['description'];
            array_push($categories, $category);
        }
        return $categories;
    }
    
    public static function loadsAll() {
        $result = mysql_query("select id,name,description from category");
        $categories = array();
        while ($row = mysql_fetch_array($result)) {
            $category = new Category();
            $category->id = $row['id'];
            $category->name = $row['name'];
            $category->description = $row['description'];
            array_push($categories, $category);
        }
        return $categories;
    }
    
    public static function loadsForJSON($start,$limit){
        return json_encode(ArrayUtil::arrayOfObjectToArray(Category::loads($start,$limit)));
    }
    
    public static function loadForJSON($id){
        return json_encode(ArrayUtil::arrayOfObjectToArray(Category::load($id)));
    }

}

?>
